<!-- 正文开始 -->
<div class="layui-fluid" id="shiftPlanSearch">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar" lay-filter="shiftPlanSearch">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-label">科室</label>
                        <div class="layui-inline item">
                            <select name="deptCode" lay-filter="shiftPlan-deptCode" >
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-label">年月</label>
                        <div class="layui-inline item">
                            <input name="ym" class="layui-input" type="text"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-inline item">
                            <select name="staffType" lay-filter="shiftPlan-staffType">
                                <option value="0">护士</option>
                                <option value="1">医生</option>
                            </select>
                        </div>
                        <div class="layui-inline">
                            <input name="staffName" class="layui-input" type="text"  lay-filter="shiftPlan-staffName"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn icon-btn btnSearch"><i class="layui-icon layui-icon-search"></i>搜索</button>
                        <button type="button" class="layui-btn icon-btn btnSave layui-btn-normal"><i class="layui-icon layui-icon-ok"></i>保存</button>
                    </div>
                </div>
            </div>
            <div class="shiftPlanTableWrapper">
                <table class="layui-table" id="shiftPlanTable" lay-filter="shiftPlanTable" class="layui-hide"></table>
            </div>
        </div>
    </div>
</div>

<style>
    #shiftPlanSearch .jzr-full-cell:focus{
        border: solid 3px red;
    }
    #shiftPlanSearch .item{
        width: 90px !important;
    }
    #shiftPlanSearch .layui-table-header .layui-table-cell {
        height: auto;
        line-height: 20px;
        padding: 0px;
        position: relative;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
    }
</style>

<script>
    layui.use(['table', 'form','http', 'tools','contextMenu','laydate'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var http = layui.http;
        var tools = layui.tools;
        var contextMenu = layui.contextMenu;
        var laydate = layui.laydate;

        var $view = $("#shiftPlanSearch");
        var $tbView = $view.find(".shiftPlanTableWrapper");
        var $deptCode = $view.find("select[name='deptCode']");
        var $staffName = $view.find("input[name='staffName']");
        var $yearMonthInput = $view.find("input[name='ym']");
        var $staffTypeSelect = $view.find("select[name='staffType']");
        var shiftTypeObjs = {};

        $yearMonthInput.val(tools.formatYearMonth(new Date(),"-"));

        var fnGetShiftType = function (code) {
            for(var key in shiftTypeObjs){
                var item = shiftTypeObjs[key];
                if(item.code == code){
                    return item;
                }
            }
            return null;
        };
        var fnGetType = function(d,f){
            var fVal = "";
            var typeName = "";
            var fontColor = "#000";
            var bgColor = "#fff";

            if(d && f) {
                fVal = d[f];
                if(fVal) {
                    var typeObj = shiftTypeObjs[fVal];
                    if (typeObj) {
                        typeName = typeObj.name1;
                        fontColor = typeObj.fontColor;
                        bgColor = typeObj.bgColor;
                    }
                }
            }
            return '<span tabindex="0" class="jzr-full-cell layui-unselect" style="cursor: pointer; background-color:' + bgColor + ';color:'+ fontColor + ';" value="' + (fVal||'') + '">' + typeName + '</span>';
        };
        var fnSetCellValue = function (idx,code,field,cellSpan) {
            var typeObj = fnGetShiftType(code);
            if(!typeObj){return;}
            var val = typeObj.id;  //排班值

            var row = shiftPlanTableIns.getCache()[idx];
            var data = {};
            data.staffId=row.staffId;
            data.id = row.id;
            data[field] = val;
            $(cellSpan).attr("value",val)
                .text(typeObj.name1)
                .css("background-color",typeObj.bgColor)
                .css("color",typeObj.fontColor);
            shiftPlanTableIns.saveDelta(idx,data);
        };
        var fnGetStartDate = function(){
            var ym = $yearMonthInput.val();
            return tools.stringToDate(ym+'-01');
        };
        var fnGetEndDate = function () {
            var ym = $yearMonthInput.val();
            var lastDay = tools.lastDay(ym+'-01');
            return tools.stringToDate(ym+'-'+(lastDay<10 ? '0':'')+lastDay);
        };
        var fnGetFieldName = function(yy,mm,dd){
            return 'd'+dd;
            //return 'd'+(yy-2000)+(mm<10 ? '0':'')+mm+(dd<10 ? '0':'')+dd;
        };
        var fnGetFieldList = function () {
            var list = [];
            var d = fnGetStartDate();
            var maxDate = fnGetEndDate();
            while (d <= maxDate) {
                var yy = d.getFullYear();
                var mm = d.getMonth() + 1;
                var dd = d.getDate();
                var field = fnGetFieldName(yy, mm, dd);
                list.push(field);
                d.setDate(d.getDate()+1);
            }
            return list;
        };
        var fnGetDateList = function () {
            var list = [];
            var d = fnGetStartDate();
            var maxDate = fnGetEndDate();
            while (d <= maxDate) {
                var yy = d.getFullYear();
                var mm = d.getMonth() + 1;
                var dd = d.getDate();
                list.push(yy+'-'+(mm<10?'0':'')+mm+'-'+(dd<10?'0':'')+dd);
                d.setDate(d.getDate()+1);
            }
            return list;
        };
        var fnCreateContextMenu = function(idx){
            var menus = [];
            for(var key in shiftTypeObjs){
                var item = (function(typeObj,idx){
                    return {
                        name: typeObj.code + ' ' + typeObj.name1,
                        click: function(){
                            var row = shiftPlanTableIns.getCache()[idx];
                            var data = {
                              staffId: row.staffId,
                              id: row.id
                            };
                            var list = fnGetFieldList();
                            layui.each(list,function(index,item){
                                data[item] = typeObj.id;
                            });
                            $tbView.find(".layui-table-body tr[data-index='" + idx + "'] span")
                                .attr("value",typeObj.id)
                                .text(typeObj.name1)
                                .css("background-color",typeObj.bgColor)
                                .css("color",typeObj.fontColor);
                            shiftPlanTableIns.saveDelta(idx,data);
                        }
                    };
                })(shiftTypeObjs[key],idx);
                menus.push(item);
            }
            return menus;
        };

        var fnLightMonday = function(){
            var d = fnGetStartDate();
            var maxDate = fnGetEndDate();
            while (d <= maxDate) {
                var yy = d.getFullYear();
                var mm = d.getMonth() + 1;
                var dd = d.getDate();
                var field = fnGetFieldName(yy, mm, dd);
                if(d.getDay() == 1){ //星期一
                    $tbView.find('th[data-field="' + field + '"] div').css("border-left","2px solid red");
                }
                d.setDate(d.getDate()+1);
            }
        };
        var fnKeyToCode = function (which) {
            if(which>=48 && which<=57){
                return which - 48;
            }
            if(which>=96 && which<=105){
                return which - 96;
            }
            return undefined;
        };
        tools.select.deptCodeOptions($deptCode);

        laydate.render({
            elem:$yearMonthInput.selector,
            type:'month',
            format:'yyyy-MM',
            value:tools.formatYearMonth(new Date(),"-"),
            showBottom:false,
            ready: function(date){
                $(".layui-laydate").off('click').on('click','.laydate-month-list li',function(){
                    $(".layui-laydate").remove();
                });
            },
            change:function(value, date) {
                $yearMonthInput.val(value);
                fnSearch();
                $staffName.focus();
            }
        });
        $yearMonthInput.on('change',function () {
           fnSearch();
        });

        form.render('select','shiftPlanSearch');

        var getSearchParam = function () {
            var param = {};
            param.deptCode = $deptCode.val();
            param.staffType = $staffTypeSelect.val();
            param.staffName = $staffName.val();
            param.y = fnGetStartDate().getFullYear();
            param.m = fnGetStartDate().getMonth()+1;
            return param;
        };
        var shiftPlanTableIns = null;
        //渲染表格
        var fnRenderTable = function() {
            var d = fnGetStartDate();
            var title = $staffTypeSelect.find("option:selected").text();
            var cols = [
                {type: 'numbers', fixed: 'left'},
                {field: 'staffName', title: '&nbsp;&nbsp;'+title+'<br/>&nbsp;&nbsp;'+(d.getMonth()+1)+'月', width: 60, fixed: 'left',style:'cursor: pointer;'}
                ];
            var maxDate = fnGetEndDate();
            while (d <= maxDate){
                var yy = d.getFullYear();
                var mm = d.getMonth()+1;
                var dd = d.getDate();
                var field = fnGetFieldName(yy,mm,dd);
                var title = dd+'号'+'<br/>周'+tools.getWeekName(d.getDay());
                cols.push({field: field, title: title, width: 45, align: 'center', templet: fnGetType});
                d.setDate(d.getDate()+1);
            }
            return table.render({
                id: "shiftPlanTable",
                elem: "#shiftPlanTable",
                method: 'post',
                contentType: "application/json",
                url: http.base_server + 'shiftPlan/list',
                where: getSearchParam(),
                page: false,
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                cellMinWidth: 40,
                height: 'full-200',
                cols: [cols],
                error: function (code, msg) {
                    http.fail(code, msg);
                },
                done: function () {
                    $tbView.find(".jzr-full-cell").keydown(function(event) {
                        var that = this;
                        if ((event.which >= 37 && event.which <= 40) || event.which == 13) {
                            tools.focusOther($tbView.find('.jzr-full-cell'),that, event.which);
                        }
                        if((event.which>=48 && event.which<=57) || (event.which>=96 && event.which<=105)){ //数字
                            //var code = event.key;  //排班代码
                            var code = fnKeyToCode(event.which);
                            var idx = $(that).parents("tr").eq(0).attr("data-index");
                            var field = $(that).parents("td").eq(0).attr("data-field");
                            fnSetCellValue(idx,code,field,that);
                        }
                        if (event !== void 0) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    });
                    $tbView.find(".layui-table-body td[data-field='staffName']").click(function(e){
                        var that = this;
                        var idx = $(that).parents("tr").eq(0).attr("data-index");
                        var x = $(that).offset().left;
                        var y = $(that).offset().top + $(that).outerHeight();
                        contextMenu.show(fnCreateContextMenu(idx),x,y);
                        if (e !== void 0) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    });
                    $tbView.find(".jzr-full-cell").focus(function(event){
                        var that = this;
                        var field = $(that).parents("td").eq(0).attr("data-field");
                        shiftPlanTableIns.lightColHeader(field,true);
                        if (event !== void 0) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    }).blur(function(event){
                        var that = this;
                        var field = $(that).parents("td").eq(0).attr("data-field");
                        shiftPlanTableIns.lightColHeader(field,false);
                        if (event !== void 0) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    });
                    fnLightMonday();
                    $tbView.find(".layui-table-body").off('click mouseenter mouseleave','td');
                }
            });
        };

        http.get("shiftType/codeList",{},function (res) {
            if(res.ok){
                layui.each(res.data,function (index,item) {
                   shiftTypeObjs[item.id] = item;
                });
                shiftPlanTableIns = fnRenderTable();
            }
        });

        var fnSearch = function(){
            shiftPlanTableIns = fnRenderTable();
            // var param = getSearchParam();
            // shiftPlanTableIns.reload({where: param});
        };

        // 搜索按钮点击事件
        $view.find(".btnSearch").click(function (event) {
            if(event.which == 13){
                return;
            }
            fnSearch();
            $staffName.focus();
        });

        form.on('select(shiftPlan-deptCode)',function(data){
            fnSearch();
        });
        form.on('select(shiftPlan-staffType)',function(data){
            fnSearch();
        });
        $view.find(".btnSave").click(function () {
            var delta = shiftPlanTableIns.getDelta();
            if(!delta || delta.length <= 0){return;}
            layui.each(delta,function(idx,item){
               item.deptCode=$deptCode.val();
               item.staffType=$staffTypeSelect.val();
               item.y = fnGetStartDate().getFullYear();
               item.m = fnGetStartDate().getMonth()+1;
            });
            http.post('shiftPlan/saveBatch',JSON.stringify(delta),function(res){
                if(res.ok){
                    shiftPlanTableIns.updateCache(res.data);
                    shiftPlanTableIns.resetDelta();
                    http.okMsg(res.msg);
                }
            });
        });

    });

</script>